package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.LoginDao;
import dao.TouristDao;
import model.Tourist;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		String type = request.getParameter("type1");
		if (null != type && type.equals("admin")) {
			if (LoginDao.loginCheckByAdmin(email, password)) {
				String user = "1";
				session.setAttribute("user", user);
				response.sendRedirect("admin/AdminViewList.jsp");
			} else {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(
						"<html><head><meta charset='UTF-8'></head><script>alert('用户名或密码错误!');window.location.href='admin/Login.jsp'</script>");
			}
		} else {
			if (LoginDao.loginCheckByTourist(email, password)) {
				Tourist tourist = TouristDao.getTouristByEmail(email);
				String user = "0";
				session.setAttribute("user", user);
				session.setAttribute("tourist", tourist);
				response.sendRedirect("index.jsp");
				System.out.println("用户"+tourist.getName()+"登陆成功");
			} else {
				try {
					response.setContentType("text/html;charset=utf-8");
					PrintWriter out = response.getWriter();
					out.print(
							"<html><head><meta charset='UTF-8'></head><script>alert('用户名或密码错误!');window.location.href='Login.html'</script>");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
